package cc.mrbird.febs.web.controller;

import cc.mrbird.febs.common.domain.FebsResponse;
import cc.mrbird.febs.common.exception.FebsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("hbase")
public class HbaseController {
    private String message;


    @PostMapping("upload")
    public FebsResponse uploadMessage(@RequestParam("files") MultipartFile[] files, @RequestParam("type") String type) throws FebsException {
        try {
            if (files.length == 0) {
                throw new FebsException("导入数据为空");
            }
            String dirPath = System.getProperty("user.dir");
            for (MultipartFile file: files) {
                String filename = file.getOriginalFilename();
//            String fileSuffix = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
                String newFileName = new Date().getTime() + filename;

                String path = File.separator + "uploadImg" + File.separator + newFileName;
                File destFile = new File(dirPath + path);
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(destFile);
                    // 将相对路径返回给前端
                    new FebsResponse().data(path);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("upload pic error");
                    return null;
                }
            }

            return new FebsResponse().data("");
        } catch (Exception e) {
            message = "导入Excel数据失败," + e.getMessage();
            log.error(message);
            throw new FebsException(message);
        }
    }
}
